using System;
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;

namespace AK.R2D.Utility.Scene.Transition
{
    public class TransitionManager : MonoBehaviour
    {
        [SerializeField] private bool useDontDestroyOnLoad = true;
        public static TransitionManager Instance { get; private set; }

        
        private void Awake()
        {
            // Enforce singleton pattern
            if (Instance && Instance != this)
            {
                Destroy(gameObject);
                return;
            }

            Instance = this;
            if (useDontDestroyOnLoad)
            {
                DontDestroyOnLoad(gameObject); // Optional: makes it persist between scenes
            }
        }

        private void Start()
        {
            StartCoroutine(loadAndActiveScene(GameSettings.Instance.DefaultMapName));
        }

        private IEnumerator loadAndActiveScene(string sceneName)
        {
            yield return SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive);
            
            var scene = SceneManager.GetSceneAt(SceneManager.sceneCount - 1);
            SceneManager.SetActiveScene(scene);
            
        }

        private IEnumerator transitionToScene(string sceneName) {
            yield return SceneManager.UnloadSceneAsync(SceneManager.GetActiveScene());

            yield return loadAndActiveScene(sceneName);
        }
    }
}
